package com.mall.common.captcha;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;

import com.octo.captcha.CaptchaException;
import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;

public class FileReaderRandomBackgroundGenerator implements BackgroundGenerator {
	private static final String IMAGE_PATH = "/com/mall/common/captcha/captcha_bg_";// 随机背景图片路径
	private int height = 100;
	private int width = 200;
	private int imageSize = 62;
	private String suffix = ".jpg";
	Random myRandom = new SecureRandom();
	private List<BufferedImage> images = new ArrayList<BufferedImage>();

	public FileReaderRandomBackgroundGenerator(Integer width, Integer height) {
		this.width = (width != null ? width.intValue() : this.width);
		this.height = (height != null ? height.intValue() : this.height);
		for(int i = 0; i < imageSize;i++){
			InputStream is = this.getClass().getResourceAsStream(IMAGE_PATH + i + suffix);
			if(is != null){
				BufferedImage out = getImage(is);
				if (out != null) {
					this.images.add(out);
				}
			}
		}
		if (this.images.isEmpty()){
			throw new CaptchaException("Root path directory is valid but does not contains any image (jpg) files");
		}
	}

	private static BufferedImage getImage(InputStream is) {
		try {
			return ImageIO.read(is);
		} catch (IOException e) {
			throw new CaptchaException("Unknown error during file reading ", e);
		}
	}

	@Override
	public BufferedImage getBackground() {
		return (BufferedImage) this.images.get(this.myRandom
				.nextInt(this.images.size()));
	}

	@Override
	public int getImageHeight() {
		return this.height;
	}

	@Override
	public int getImageWidth() {
		return this.width;
	}

}
